<?php

namespace App\Models;

use App\Constant\SmsTemplate;
use App\Events\SmsSendEvent;
use App\Exceptions\GeneralException;
use App\Models\Traits\Repay;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;

/**
 * App\Models\LoanApply
 *
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\LoanApply newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\LoanApply newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\LoanApply query()
 * @mixin \Eloquent
 * @property int $id
 * @property int $loan_request_id 授信申请表id
 * @property string $loan_id 新流订单号
 * @property int $amount 总金额存分
 * @property int $period 分期数
 * @property int $loan_status 申请状态
 * @property int $user_id 当前操作用户id
 * @property string|null $ip 用户ip
 * @property string|null $loan_time 放款成功时间
 * @property string $message 资方返回信息
 * @property string $trans_money_list 分账明细
 * @property float $lending_rate 贷款费率
 * @property float $insurance_rate 前置保险费
 * @property float $month_insurance_rate 月保险费率
 * @property float $manage_rate 管理费率
 * @property float $repayment_rate 提前还清手续费
 * @property float $fines_rate 逾期罚息利率
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @property-read mixed $loan_request
 * @property-read mixed $trans_money_list_format
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\LoanApply byLoanId($loanId)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\LoanApply whereAmount($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\LoanApply whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\LoanApply whereFinesRate($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\LoanApply whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\LoanApply whereInsuranceRate($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\LoanApply whereIp($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\LoanApply whereLendingRate($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\LoanApply whereLoanId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\LoanApply whereLoanRequestId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\LoanApply whereLoanStatus($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\LoanApply whereLoanTime($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\LoanApply whereManageRate($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\LoanApply whereMessage($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\LoanApply whereMonthInsuranceRate($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\LoanApply wherePeriod($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\LoanApply whereRepaymentRate($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\LoanApply whereTransMoneyList($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\LoanApply whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\LoanApply whereUserId($value)
 * @property float $pre_insurance_amt 前置险金额
 * @property int $bank_card_id 用户选择的放款银行卡id
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\LoanApply loanTimeEnd($timeStart)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\LoanApply loanTimeStart($timeStart)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\LoanApply whereBankCardId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\LoanApply wherePreInsuranceAmt($value)
 * @property string $sub_code 对应新流返回的子状态值subCode
 * @property string $loan_sign 对应新流返回的签名sign，异常时可做校验请求数据用
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\LoanApply whereLoanSign($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\LoanApply whereSubCode($value)
 * @property float $arrival_account 实际到账金额
 * @property float $performance_insurance 用户履约保险
 * @property string $out_trade_id 合作方借款id
 * @property-read \App\Models\UserBankCard $bankCard
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\LoanApply byUid($uid)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\LoanApply whereArrivalAccount($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\LoanApply whereOutTradeId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\LoanApply wherePerformanceInsurance($value)
 */
class LoanApply extends Model
{
    use SoftDeletes;
    protected $table = 'loan_apply';


    protected $guarded = [
        'id',
    ];

    protected $dates = ['delete_at'];


    CONST LOAN_STATUS_INIT = 0;
    /**
     * 放款处理中
     */
    CONST LOAN_STATUS_PROCESSING = 1;

    /**
     * 放款成功
     */
    CONST LOAN_STATUS_SUCCESS = 2;



    /**
     * 放款失败
     */
    CONST LOAN_STATUS_FAIL = 3;


    /**
     * 需要换卡
     */
    CONST LOAN_CHANGE_CARD = 4;

    /**
     * 放款限额，需要凌晨重新发起放款
     */
    CONST LOAN_RETRY_APPLY = 99;

    /*
     * 正在处理
     */
    const LOAN_CHANGE_CARD_HANDLING = 5;
    /**
     * 人工处理结果换卡后放款成功
     */
    CONST LOAN_HANDLE_CHANGE_CARD_SUCCESS = 6;

    /**
     * 人工处理结果换卡后放款失败
     */
    CONST LOAN_HANDLE_CHANGE_CARD_FAIL = 7;

    /**
     * 如果用户有这些状态不能再申请新的授信、放款
     */
    const CAN_NOT_LOAN = [
        self::LOAN_STATUS_PROCESSING,
        self::LOAN_CHANGE_CARD_HANDLING,
    ];
    /**
     * 状态文本映射
     */
    const  LOAN_STATUS_TEXT = [
        self::LOAN_STATUS_INIT => '放款初始', // 0
        self::LOAN_STATUS_PROCESSING => '放款处理中',  // 1
        self::LOAN_STATUS_SUCCESS => '放款成功',  // 2
        self::LOAN_STATUS_FAIL => '放款失败',  //  3
        self::LOAN_CHANGE_CARD => '需要换卡',  // 4
        self::LOAN_CHANGE_CARD_HANDLING => '换卡结果处理中',  // 5
        self::LOAN_HANDLE_CHANGE_CARD_SUCCESS => '换卡处理成功', // 6
        self::LOAN_HANDLE_CHANGE_CARD_FAIL => '换卡处理失败',  //7
        self::LOAN_RETRY_APPLY => '放款限额，需要凌晨重新发起放款',  //99
    ];


    const  RATE_KEY = [
        'lending_rate',
        'insurance_rate',
        'month_insurance_rate',
        'manage_rate',
        'repayment_rate',
        'fines_rate',
    ];


    /**与上面的 2 没有关系
     * 重试放款成功
     */
    CONST TRY_LOAN_STATUS_SUCCESS = 2;

    /**与上面的 1 没有关系
     * 已经重新发起放款标记
     */
    CONST TRY_LOAN_MARK = 1;

    /**
     * 重试放款初始值 与上面的 0 没有关系
     * @param $q
     * @param $loanI
     */
    CONST INIT_LOAN_STATUS = 0;

    /**
     * 发送短信 jpush 消息 标识 0 未发 1 已发
     * @param $q
     * @param $loanI
     */
    CONST IS_SEND_SMS = 0;
    CONST SEND_SMS = 1;



    public function scopeByLoanId($q, $loanId)
    {
        return $q->where('loan_id', $loanId);
    }

    /**
     * 用户id查询作用域
     * @param $q
     * @param $uid
     * @return mixed
     * @author luwei
     * @date 2019-01-13 23:01
     */
    public function scopeByUid($q, $uid)
    {
        return $q->where('user_id', $uid);
    }

    /**
     * Description: 获取放款用户信息
     * Author: liuju
     * DateTime: 2019-01-31 15:38
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function getUser()
    {
        return $this->hasOne(User::class,'id','user_id');
    }

    public function  getSummary()
    {
        return $this->hasOne(RepaySummary::class,'loan_id','loan_id');
    }
    /**
     * Description: 获取放款时间大于给定时间的数据
     * Author: liuju
     * DateTime: 2019-01-09 14:38
     * @param $query
     * @param $timeStart
     * @return mixed
     */
    public function scopeLoanTimeStart($query, $timeStart)
    {
        $timeStart = date('Y-m-d 00:00:00', strtotime($timeStart));
        return $query->whereNotNull('loan_time')->where('loan_time', '>=', $timeStart);
    }

    /**
     * Description: 获取放款时间小于给定时间的数据
     * Author: liuju
     * DateTime: 2019-01-09 14:41
     * @param $query
     * @param $timeStart
     * @return mixed
     */
    public function scopeLoanTimeEnd($query, $timeStart)
    {
        $timeStart = date('Y-m-d 00:00:00', strtotime($timeStart));
        return $query->whereNotNull('loan_time')->where('loan_time', '<=', $timeStart);
    }


    /**
     * Description:分账明细设为json
     * Author: liuju
     * DateTime: 2019-01-11 16:18
     * @param $value
     * @return false|string
     */
    public function setTransMoneyListAttribute($value)
    {
        return $this->attributes['trans_money_list'] = is_array($value) ? json_encode($value, JSON_UNESCAPED_UNICODE) : '';
    }

    /**
     * Description: 分账明细转为数组
     * Author: liuju
     * DateTime: 2019-01-11 16:19
     * @return array|mixed
     */
    public function getTransMoneyListAttribute($value)
    {
        return !empty($value) ? json_decode($value, true) : [];
    }

    /**
     * Description: 设置借款金额总量以分为单位
     * Author: liuju
     * DateTime: 2019-02-20 17:24
     * @param $value
     * @return string
     */
    public function setAmountAttribute($value)
    {
        return $this->attributes['amount'] = bcmul($value,100,2);
    }

    /**
     * Description:获取借款金额总量
     * Author: liuju
     * DateTime: 2019-02-20 17:25
     * @param $value
     * @return string|null
     */
    public function getAmountAttribute($value)
    {
        return  bcdiv($value,100,2);
    }

    /**
     * Description: 设置到款金额总量以分为单位
     * Author: liuju
     * DateTime: 2019-02-20 17:24
     * @param $value
     * @return string
     */
    public function  setArrivalAccountAttribute($value)
    {
        return $this->attributes['arrival_account'] = bcmul($value,100,2);
    }

    /**
     * Description: 获取到款金额总量
     * Author: liuju
     * DateTime: 2019-02-20 17:24
     * @param $value
     * @return string
     */
    public function  getArrivalAccountAttribute($value)
    {
        return bcdiv($value,100,2);
    }

    /**
     * Description: 设置前置险金额总量以分为单位
     * Author: liuju
     * DateTime: 2019-02-20 17:24
     * @param $value
     * @return string
     */
    public function setPreInsuranceAmtAttribute($value)
    {
        return  $this->attributes['pre_insurance_amt'] =  bcmul($value,100,2);
    }

    /**
     * Description:获取前置险金额
     * Author: liuju
     * DateTime: 2019-02-20 17:40
     * @param $value
     * @return string|null
     */
    public function getPreInsuranceAmtAttribute($value)
    {
        return bcdiv($value,100,2);
    }


    /**
     * Description: 设置履约险金额以分为单位
     * Author: liuju
     * DateTime: 2019-02-20 17:42
     * @param $value
     * @return string
     */
    public function setPerformanceInsuranceAttribute($value)
    {
        return $this->attributes['performance_insurance'] = bcmul($value,100,2);
    }

    public  function  getPerformanceInsuranceAttribute($value)
    {
        return bcdiv($value,100,2);
    }

    /**
     * Description:获取关联的授信数据
     * Author: liuju
     * DateTime: 2019-01-11 16:20
     * @return UserLoanRequest|UserLoanRequest[]|\Illuminate\Database\Eloquent\Collection|Model|null
     */
    public function getLoanRequestAttribute()
    {
        return UserLoanRequest::find($this->loan_request_id);
    }


    /**
     * Description:获取用户最新的一次目的为放款的换卡记录
     * Author: liuju
     * DateTime: 2019-01-11 16:56
     * @return Model|\Illuminate\Database\Eloquent\Relations\HasOne|object|null
     */
    public function getRelationChangeCardRecord()
    {
        return $this->hasOne(UserChangeBankCardRecord::class, 'loan_id', 'loan_id')
            ->where('purpose', UserChangeBankCardRecord::PURPOSE_LOAN)
            ->orderByDesc('id');
    }


    /**
     * Description: 通过分账明细获取实际到账和前置险结果
     * Author: liuju
     * DateTime: 2019-01-12 11:04
     * @param $transMoneyList
     * @return array
     */
    public static function getDetailByTransMoneyList($transMoneyList)
    {
        //实际到账金额
        $arrivalAccount = 0;
        //前置险扣除
        $preInsuranceAmt = 0;
        //履约险金额
        $performanceInsurance = 0;
        if ($transMoneyList) {
            foreach ($transMoneyList as $item) {
                if (!empty($item['transType'])) {
                    if ($item['transType'] === '03') {
                        $arrivalAccount = $item['transAmt'];
                    }
                    if($item['transType'] === '02'){
                       $performanceInsurance = $item['transAmt'];
                    }
                    if ($item['transType'] === '01') {
                        $preInsuranceAmt = $item['transAmt'];
                    }

                }
            }
        }
        return [
            'arrival_account' => $arrivalAccount,
            'pre_insurance_amt' => $preInsuranceAmt,
            'performance_insurance' => $performanceInsurance,
        ];
    }

    /**
     * 获取用户总借记次数
     * @param $userId
     * @return int
     * @author luwei
     * @date 2019-01-10 22:32
     */
    public static function getDebitNum($userId)
    {
        $con = [
            'user_id' => $userId,
        ];
        //放款成功  换卡后放款成功
        $status = [
            self::LOAN_STATUS_SUCCESS,
            self::LOAN_HANDLE_CHANGE_CARD_SUCCESS,
        ];
        return self::where($con)->whereIn('loan_status',$status)->count();
    }

    /**
     * Description:通过返回值来判断用户放款状态
     * Author: liuju
     * DateTime: 2019-01-11 17:03
     * @param $res
     * @return int
     * @throws GeneralException
     */
    public static function getLoanStatusByRes($res)
    {
        try {
            $resStatus = !empty($res['data']['status']) ? $res['data']['status'] : $res['subCode'];
            //判断放款申请状态
            switch ($resStatus) {
                case 'S':   //放款成功
                    $status = LoanApply::LOAN_STATUS_SUCCESS;
                    break;
                case 'P':  //放款处理中
                    $status = LoanApply::LOAN_STATUS_PROCESSING;
                    break;
                case 'F': //放款失败
                    $status = LoanApply::LOAN_STATUS_FAIL;
                    break;
                case 'F16': //需要换卡
                    $status = LoanApply::LOAN_CHANGE_CARD;
                    break;
                case 'F13':
                    $status = LoanApply::LOAN_STATUS_SUCCESS;
                    break;
                default:
                    $status = LoanApply::LOAN_STATUS_FAIL;
                    //不为需要换卡的F***状态码，需要判断明细来获取是否放款成功
                        $transMoneyList = !empty($res['data']['transMoneyList']) ? $res['data']['transMoneyList'] : [];
                        if ($transMoneyList) {
                            foreach ($transMoneyList as $val) {
                                if ($val['transType'] === '03') {
                                    //分账明细中提现分账成功
                                    if($val['transStatus'] === 'S'){
                                        $status = LoanApply::LOAN_STATUS_SUCCESS;
                                        break;
                                    }
                                    //分账明细中提现分账中
                                    if($val['transStatus'] === 'P'){
                                        $status = LoanApply::LOAN_STATUS_PROCESSING;
                                        break;
                                    }
                                }
                            }
                        }
                    break;
            }
            return $status;
        } catch (\Exception $e) {
            throw  new GeneralException($e->getMessage());
        }
    }

    /**
     * Description: 按照date格式，获取放款成功数据
     * Author: liuju
     * DateTime: 2019-01-09 19:55
     * @param $timeStart
     * @param $timeEnd
     * @param int $pageNum
     * @param int $pageSize
     * @return array
     */
    public static function getList($timeStart, $timeEnd, $pageNum = 1, $pageSize = 25)
    {

        $columns = [
            DB::raw('date_format(loan_time,"%Y-%m-%d") as loan_date'),
            DB::raw('count(id) as loan_total'),
            DB::raw('sum(arrival_account) as loan_money_sum'),
            DB::raw('sum(amount - pre_insurance_amt) as amt_sum'),
        ];
        $loan_apply = new LoanApply();
        $loan_apply->setConnection('backend');
        $query = $loan_apply->whereIn('loan_status', [self::LOAN_STATUS_SUCCESS,self::LOAN_HANDLE_CHANGE_CARD_SUCCESS])
            ->groupBy(DB::raw('date_format(loan_time,"%Y-%m-%d")'))
            ->orderByDesc(DB::raw('date_format(loan_time,"%Y-%m-%d")'));
        //查询在开始时间之后的数据
        $timeStart && $query->loanTimeStart($timeStart);
        //查询在结束时间之前的数据
        $timeEnd && $query->loanTimeEnd($timeEnd);

        if ($pageNum === 0) {
            return [
                'total' => $query->count(),
                'data' => $query->get($columns),
            ];
        }
        $res = $query->paginate($pageSize, $columns, 'l', $pageNum)->toArray();
        foreach ($res['data'] as $key=>$item) {
            $res['data'][$key]['loan_money_sum'] = bcdiv($item['loan_money_sum'],100,2);
            $res['data'][$key]['amt_sum'] = bcdiv($item['amt_sum'],100,2);
        }
        return [
            'total' => $res['total'],
            'list' => $res['data'],
        ];

    }


    /**
     * Description: 通过制定date获取当天放款成功数据
     * Author: liuju
     * DateTime: 2019-01-09 20:15
     * @param $date
     * @param int $pageNum
     * @param int $pageSize
     * @return array
     */
    public static function getLoanSuccessRecodeByDay($date, $pageNum = 1, $pageSize = 25)
    {
        $columns = [
            'loan_apply.id',
            'loan_apply.arrival_account as amount',
            DB::raw('loan_apply.amount - loan_apply.arrival_account'),
            'loan_apply.period',
            'loan_apply.loan_id',
            'loan_apply.loan_time',
            'loan_apply.user_id',
            'user_bank_cards.phone_num',
            'user_bank_cards.card_username as name',
        ];


        $query = (new LoanApply())->setConnection('backend')->whereIn('loan_apply.loan_status', [self::LOAN_STATUS_SUCCESS,self::LOAN_HANDLE_CHANGE_CARD_SUCCESS])
            ->leftJoin('user_bank_cards', 'loan_apply.bank_card_id', 'user_bank_cards.id')
            ->whereDate('loan_apply.loan_time', $date)
            ->orderByDesc('loan_apply.loan_time');
        if ($pageNum === 0) {
            return [
                'total' => $query->count(),
                'data' => $query->get($columns)->toArray(),
            ];
        }

        $res = $query->paginate($pageSize, $columns, '', $pageNum)->toArray();

        return [
            'total' => $res['total'],
            'list' => $res['data'],
        ];
    }


    /**
     * Description: 获取换卡列表
     * Author: liuju
     * DateTime: 2019-01-12 11:51
     * @param $timeStart
     * @param $timeEnd
     * @param int $pageNum
     * @param int $pageSize
     * @return array
     */
    public static function getChangeCardList($timeStart, $timeEnd, $pageNum = 1, $pageSize = 25)
    {

        $query = (new LoanApply())->setConnection('backend')->with('getRelationChangeCardRecord')
            ->leftJoin('users','users.id','loan_apply.user_id')
            ->leftJoin('user_bank_cards', 'user_bank_cards.id', 'loan_apply.bank_card_id')
            ->leftJoin('user_loan_requests', 'user_loan_requests.id', 'loan_apply.loan_request_id')
            ->leftJoin('setting_channels', 'setting_channels.channel_code', 'user_loan_requests.channel')
            ->whereIn('loan_status', [self::LOAN_CHANGE_CARD,self::LOAN_CHANGE_CARD_HANDLING, self::LOAN_HANDLE_CHANGE_CARD_SUCCESS, self::LOAN_HANDLE_CHANGE_CARD_FAIL])
            ->orderByDesc('loan_apply.id');

        $timeStart && $query->loanTimeStart($timeStart);
        $timeEnd && $query->loanTimeEnd($timeEnd);

        $columns = [
            'loan_apply.id',
            'loan_apply.user_id',
            'loan_apply.created_at',
            'loan_apply.out_trade_id as trade_id',
            'loan_apply.loan_id',
            'loan_apply.amount',
            'loan_apply.period',
            'loan_apply.message',
            'loan_apply.loan_status',
            'loan_apply.created_at',
            'user_bank_cards.card_num as fail_card_num',
            'user_bank_cards.card_username',
            'users.phone_num',
            'user_bank_cards.bank_name_show as fail_card_bank_name',
            'setting_channels.channel_name',
        ];

        $total = 0;
        $list = [];
        if ($pageNum === 0) {
            $total = $query->count();
            $list = $query->get($columns)->toArray();
        } else {
            $res = $query->paginate($pageSize, $columns, 'l', $pageNum)->toArray();
            $total = $res['total'];
            $list = $res['data'];
        }
        foreach ($list as $key => $item) {
            $list[$key]['created_date'] = date('Y-m-d', strtotime($item['created_at']));
            $list[$key]['created_time'] = date('H:i:s', strtotime($item['created_at']));
            unset($list[$key]['create_at']);
            $time1 = strtotime($item['created_at']);
            $list[$key]['new_card_num'] =  '';
            $list[$key]['new_card_bank_name'] = '';
            if($item['get_relation_change_card_record']){
               $time2 = strtotime($item['get_relation_change_card_record']['created_at']);
               if($time2 > $time1){
                   $list[$key]['new_card_num'] = $item['get_relation_change_card_record']['card_num'] ;
                   $list[$key]['new_card_bank_name'] = $item['get_relation_change_card_record']['bank_name'];
               }
            }
            unset($list[$key]['get_relation_change_card_record']);
            if($pageNum ==0){
                $list[$key]['fail_card_num'] .= '('.$item['fail_card_bank_name'].')';
                $list[$key]['new_card_num'] .= $list[$key]['new_card_bank_name']? '('.$list[$key]['new_card_bank_name'].')':'';
                $list[$key]['status_text'] = self::LOAN_STATUS_TEXT[$item['loan_status']];
            }
        }
        return [
            'total' => $total,
            'list' => $list,
        ];
    }

    /**
     * Description:放款信息与银行卡一对一关联
     * Author: Sam
     * DateTime: 2019/1/13 17:51
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function bankCard()
    {
        return $this->hasOne(UserBankCard::class,'id','bank_card_id');
    }

    /**
     * 实际到账金额
     * @param UserLoanRequest $loan
     * @return float|mixed
     * @author luwei
     * @date 2019-02-28 13:50
     */
    public static function receiveMoney(UserLoanRequest $loan){
        $apply = LoanApply::where('loan_request_id',$loan->id)->first();
        $receiveMoney = $apply->arrival_account;
        return $receiveMoney;
    }
    /**
     * Description: 通过授信ID获取当前授信数据放款的状态
     * Author: Liuju
     * DateTime: 2019-03-01 15:12
     * @param $id
     * @return int
     */
    public  static function  getStatusByLoanRequestId($id)
    {
        /**
         * 放款成功 2 6
         * 放款中 1 4
         * 放款失败 3 7
         */
        return  self::where(['loan_request_id' => $id])->value('loan_status');

    }

    /**
     * Description: 通过授信ID获取当前当前授信数据放款结果的投保单号
     * Author: Liuju
     * DateTime: 2019-03-01 16:45
     * @param $id
     * @return bool|int
     */
    public  static function  getPayOrderByLoanRequestId($id)
    {
       $apply = self::where(['loan_request_id' => $id])->first();
       if(!$apply){
           return false;
       }
       return Repay::getPayOrderNo($apply->trans_money_list);
    }
}
